package com.swak.rpc.config.model;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

@Getter
@Setter
@Accessors(chain = true)
public class ServiceDescriptor {
	private final String serviceName;
	private final Class<?> serviceInterfaceClass;
	private final Map<String, List<MethodDescriptor>> methods = new HashMap<>();
	private final Map<String, Map<String, MethodDescriptor>> descToMethods = new HashMap<>();

	public ServiceDescriptor(Class<?> interfaceClass) {
		this.serviceInterfaceClass = interfaceClass;
		this.serviceName = interfaceClass.getName();
		initMethods();
	}

	private void initMethods() {
		Method[] methodsToExport = this.serviceInterfaceClass.getMethods();
		for (Method method : methodsToExport) {
			method.setAccessible(true);

			List<MethodDescriptor> methodModels = methods.computeIfAbsent(method.getName(), (k) -> new ArrayList<>(1));
			methodModels.add(new MethodDescriptor(method));
		}

		methods.forEach((methodName, methodList) -> {
			Map<String, MethodDescriptor> descMap = descToMethods.computeIfAbsent(methodName, k -> new HashMap<>());
			methodList.forEach(methodModel -> descMap.put(methodModel.getParamDesc(), methodModel));
		});
	}
}
